package cn.wen.forum.task;

import cn.wen.forum.common.util.RedisUtils;
import cn.wen.forum.common.util.StringUtils;
import cn.wen.forum.constants.ForumConstant;
import cn.wen.forum.mapper.PostMapper;
import cn.wen.forum.pojo.entity.Post;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @ClassName UpdatePostDataTask
 * @Author By wen
 * @Description 定时从redis获取最新数据，同步MySQL的post表
 * @Date 2023/8/8 14:36
 * @Version 1.0
 */
@Slf4j
@Component
public class UpdatePostDataTask {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private PostMapper postMapper;


    /**
     * 每五十分钟执行一次数据同步
     */
    @Scheduled(cron = "0 0/50 * * * ?")
    public void runimpl(){
        log.info("==>同步主题帖数据至数据库定时任务开始！");
        try {
            handler();
        } catch (Exception e) {
            log.error("==>定时任务执行异常：",e);
        }
        log.info("==>同步主题帖数据至数据库定时任务结束！");
    }

    public void handler() throws Exception{
        BulkRequest bulkRequest = new BulkRequest();
        // 获取指定时间内被浏览过的帖子id的set集合，同步对应信息至数据库
        Set<String> cachePostIDSet = redisUtils.getCacheSet(ForumConstant.POST_ID);
        log.info("==>当前需要同步主题帖共计数据条数:{};id集合:[{}],",cachePostIDSet.size(),cachePostIDSet);
        for(String postID:cachePostIDSet){
            // 根据帖子id从缓存读取当前id所记录的map（收藏量，评论量）
            Map<Object, Object> cacheMap = redisUtils.getCacheMap(postID);
            Post postEntity = new Post();
            postEntity.setId(Long.parseLong(postID));
            if(StringUtils.isNotNull(cacheMap)){
                String approval = cacheMap.get(ForumConstant.APPROVAL_KEY) + "";
                String collect = cacheMap.get(ForumConstant.COLLECT_KEY) + "";
                String pageView = cacheMap.get(ForumConstant.PAGEVIEW_KEY) + "";

                postEntity.setApproval(Integer.parseInt(approval));
                postEntity.setCollect(Integer.parseInt(collect));
                postEntity.setPageView(pageView);
                // 同步更新数据库
                postMapper.updateById(postEntity);

                Post post = postMapper.selectById(postID);
                // 设置更新ES数据
                Map<String, Object> map = new HashMap<>();
                map.put("pageView",pageView);
                map.put("collect",collect);
                map.put("approval",approval);
                map.put("review",post.getReview());
                UpdateRequest updateRequest = new UpdateRequest("forum", postID)
                        .doc(map);
                bulkRequest.add(updateRequest);
            }
        }
        // 更新ES索引库
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        // 获取所有操作结果
        if (bulkResponse.hasFailures()) {
            // 处理批量更新失败的情况
            for (BulkItemResponse bulkItemResponse : bulkResponse) {
                if (bulkItemResponse.isFailed()) {
                    BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                    String documentId = bulkItemResponse.getId();
                    String failureMessage = failure.getMessage();

                    // 处理失败的文档及错误信息
                    log.info("更新文档失败，文档ID:{},错误信息:{}" ,documentId, failureMessage);
                }
            }
        } else {
            // 处理批量更新成功的情况
            for (BulkItemResponse bulkItemResponse : bulkResponse) {
                String documentId = bulkItemResponse.getId();

                // 处理成功更新的文档
                log.info("更新文档成功，文档ID:{}",documentId);
            }
        }
    }
}
